package com.itheima.Filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {

//    拦截到请求时,调用该方法,可以调用多次
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        1.获取请求资源路径
        String requestURI = request.getRequestURI();
        log.info("请求资源路径为:{}",requestURI);
        StringBuffer requestURL = request.getRequestURL();
        log.info("请求路径为: {}",requestURL.toString());

//        2.看是否包含登录路径
        if(requestURI.contains("/login")){
            log.info("登录请求,放行...");
            filterChain.doFilter(request,response);
            return ;
        }

//        3.获取请求头token
        String token = request.getHeader("token");

//        4.不是登录请求路径,查看请求中是否带着token
        if(token==null || token=="") {
            //!StringUtils.hasLength(jwt)用这个校验是否为空也可以
            response.setStatus(401);
            log.info("请求中没有Token,请求响应401");
            return;
        }

//        5.检验token是否有效
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token校验失败，报错401");
            response.setStatus(401);
            return;
        }

//        6.token校验成功，放行
        log.info("令牌合法，放行...");
        filterChain.doFilter(request,response);
    }
}
